/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Featured;
import org.cx1.model.FeaturedList;
import org.cx1.model.Listing;
import org.cx1.model.Transaction;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IAmenityService;
import org.cx1.service.api.IFeaturedService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.ITransactionService;
import org.cx1.service.impl.DAmenityService;
import org.cx1.service.impl.DFeaturedService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DTransactionService;
import org.cx1.service.impl.MFeaturedService;
import org.cx1.service.utils.FeaturedTransaction;
import org.cx1.service.utils.IDGenerator;
import org.cx1.web.controller.action.FeaturedAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class FeaturedController extends BaseController {
    
    private IFeaturedService featuredService = new MFeaturedService();
    private IFeaturedService featuredService2 = new DFeaturedService();
    private IListingService listingService = new DListingService();
    private ITransactionService transactionService = new DTransactionService();
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat sdf_utc = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat sdf_manila = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat sdf_manila2 = new SimpleDateFormat("MMMM dd, yyyy HH:ss");
    
    public FeaturedController() {
        
    }
    
    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();        
        
        String userID = SessionUtils.getUserID(request.getSession());     
        if (StringUtils.isEmpty(userID)) {
            mav.setView(new RedirectView("home.htm"));
            return mav;
        } 
        if (!StringUtils.isEmpty(userID)) {
            map.put("loggedin", true);
        }      
        
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        } 
        else {
            parameterMap = this.getFormParams(request);
        }
        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
        
        switch (action) {
            
            case FeaturedAction.FEATURED_ABOUT: {
                about(mav, map, request);
                break;
            }
            
            case FeaturedAction.READ_ALL_FEATURED_LISTING: {
                readAllFeaturedListing(userID, mav, map, request);
                break;
            }
            case FeaturedAction.CREATE_FEATURED_LISTING: {
                createFeaturedListing(userID, mav, map, request);
                break;
            }
            case FeaturedAction.DELETE_FEATURED_LISTING: {
                deleteFeaturedListing(userID, mav, map, request);
                break;
            }            
            case FeaturedAction.SUCCESS_FEATURED_LISTING: {
                successFeaturedListing(userID, mav, map, request);
                break;
            }
            case FeaturedAction.PAY_FEATURED_LISTING: {
                payFeaturedListing(userID, mav, map, request);
                break;
            }
                
            case FeaturedAction.READ_ALL_FEATURED_LISTING_MANAGE: {
                readAllFeaturedListing_manage(mav, map, request);
                break;
            }
            case FeaturedAction.CREATE_FEATURED_LISTING_MANAGE: {
                createFeaturedListing_manage(mav, map, request);
                break;
            }
            case FeaturedAction.DELETE_FEATURED_LISTING_MANAGE: {
                deleteFeaturedListing_manage(mav, map, request);
                break;
            }
                
                
                
            case FeaturedAction.READ_ALL_FEATURED_LIST: {
                readAllFeaturedList(mav, map, request);
                break;
            }
            case FeaturedAction.CREATE_FEATURED_LIST: {
                createFeaturedList(mav, map, request);
                break;
            }
            case FeaturedAction.DELETE_FEATURED_LIST: {
                deleteFeaturedList(mav, map, request);
                break;
            }
                
            default: {
                about( mav, map, request);
                break;
            }
        }  
        
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        mav.addObject("model", map);
        return mav;
    }
    
    private void about(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setView(new RedirectView("home.htm"));
    }
    
    private void readAllFeaturedListing(String userID, ModelAndView mav, Map map, HttpServletRequest request) {        
        ServiceResponse<List<Listing>> response1 = listingService.readUserListings(userID, 0, 0);
        List<Listing> listings = response1.getResponse();     
        
        //CX: mark if listing is featured        
        ServiceResponse<List<Featured>> response2 = featuredService2.readAll(0, 0);
        List<Featured> featureds = response2.getResponse();
        System.out.println("CX: " + new Date());
        markFeaturedListings(listings, featureds);
        System.out.println("CX: " + new Date());
        
        map.put("listings", listings);
        map.put("featureds", featureds);
        mav.setViewName("featuredall");   
    }
    
    private void createFeaturedListing(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        
        ServiceResponse<Listing> response1 = this.listingService.read(listingID);
        Listing listing = response1.getResponse();
        
        //CX: auto set expiry date
        Date startDate = new Date();        
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 7);        
        c.add(Calendar.HOUR, 1);             
        Date endDate = c.getTime();        
            
        sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
        String strStartDate = this.sdf_utc.format(startDate);
        String strEndDate = this.sdf_utc.format(endDate);       
        
        sdf_manila2.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));    
        String displayStartDate = this.sdf_manila2.format(startDate);
        String displayEndDate = this.sdf_manila2.format(endDate);
        
        //CX: set session transaction variables
        FeaturedTransaction trans = new FeaturedTransaction();
        String transID = IDGenerator.generateID();        
        trans.setId(transID);
        trans.setListingID(listingID);
        trans.setStartDate(startDate);
        trans.setEndDate(endDate);
        trans.setStrStartDate(strStartDate);
        trans.setStrEndDate(strEndDate); 
        trans.setDisplayStartDate(displayStartDate);
        trans.setDisplayEndDate(displayEndDate);
        
        request.getSession().setAttribute(transID, trans);
        
        //CX: write transaction to DB
        Transaction transaction = new Transaction();
        String transactionID = IDGenerator.generateID();        
        transaction.setId(transactionID);
        transaction.setFeatured_listingID(listingID);
        transaction.setFeatured_startDate(startDate);
        transaction.setFeatured_endDate(endDate);
        transaction.setFeatured_strStartDate(strStartDate);
        transaction.setFeatured_strEndDate(strEndDate);
        transaction.setFeatured_displayStartDate(displayStartDate);
        transaction.setFeatured_displayEndDate(displayEndDate);
        
        request.getSession().setAttribute(transactionID, transaction);
        
        map.put("transID", transID);
        map.put("transactionID", transactionID);
        map.put("listing", listing);
        map.put("strStartDate", strStartDate);
        map.put("strEndDate", strEndDate);
        map.put("displayStartDate", displayStartDate);
        map.put("displayEndDate", displayEndDate);
        mav.setViewName("featuredadd");
    }
        
    private void deleteFeaturedListing(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        
    }    
    
    private void successFeaturedListing(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("featuredsuccess");
    } 
    
    private void payFeaturedListing(String userID, ModelAndView mav, Map map, HttpServletRequest request) { 
        String transactionID = request.getParameter("transactionID"); 
        String transID = request.getParameter("transID"); 
        String city = request.getParameter("city"); 
        String term = request.getParameter("term");
        String strDuration = request.getParameter("duration");
        int duration = 1;
        
        if (request.getSession().getAttribute(transactionID) != null) {            
            if (!StringUtils.isEmpty(strDuration)) {
                duration = StringUtils.isEmpty(strDuration.trim()) ? 1 : Integer.parseInt(strDuration.trim());                
            }
            int dateMultiplier = 1 * duration;
            
            //CX: set start and end dates
            Date startDate = new Date();        
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DATE, 7 * dateMultiplier);        
            c.add(Calendar.HOUR, 1);             
            Date endDate = c.getTime();        

            sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
            String strStartDate = this.sdf_utc.format(startDate);
            String strEndDate = this.sdf_utc.format(endDate);       

            sdf_manila2.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));    
            String displayStartDate = this.sdf_manila2.format(startDate);
            String displayEndDate = this.sdf_manila2.format(endDate);
            
            Transaction transaction = (Transaction) request.getSession().getAttribute(transactionID);            
            String listingID = transaction.getFeatured_listingID();
            
            //CX: set transaction details
            transaction.setFeatured_city(city);
            transaction.setFeatured_termType(term);
            transaction.setId(transactionID);
            transaction.setFeatured_listingID(listingID);
            
            transaction.setFeatured_startDate(startDate);
            transaction.setFeatured_endDate(endDate);
            transaction.setFeatured_strStartDate(strStartDate);
            transaction.setFeatured_strEndDate(strEndDate);
            transaction.setFeatured_displayStartDate(displayStartDate);
            transaction.setFeatured_displayEndDate(displayEndDate);
            
            Listing listing = this.listingService.read(listingID).getResponse();
        
            //CX: for display- string version of rental term
            String strTerm = "";        
            if (StringUtils.equalsIgnoreCase("1", term)) {
                strTerm = "long term";
            }
            else if (StringUtils.equalsIgnoreCase("2", term)) {
                strTerm = "short term";
            }
        
            //CX: write transaction to DB
            ServiceResponse<String> response3 = transactionService.create(transaction);
                        
            map.put("transactionID", transaction.getId());
            map.put("listing", listing);
            map.put("city", city);
            map.put("term", strTerm);
            map.put("duration", duration);            
            map.put("strStartDate", strStartDate);
            map.put("strEndDate", strEndDate);
            map.put("displayStartDate", displayStartDate);
            map.put("displayEndDate", displayEndDate);
            mav.setViewName("featuredpay");
        }
        else {
            //CX: error
            mav.setView( new RedirectView("home.htm") );
        }
    }
        
    private void readAllFeaturedListing_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        String city = request.getParameter("city");
        String termType = request.getParameter("termType");
        
        ServiceResponse<List<Featured>> response1 = featuredService2.readAll("makati", "1", 0, 0);
        ServiceResponse<List<Featured>> response2 = featuredService2.readAll("makati", "2", 0, 0);
                   
        ServiceResponse<List<Featured>> response3 = featuredService2.readAll("taguig", "1", 0, 0);
        ServiceResponse<List<Featured>> response4 = featuredService2.readAll("taguig", "2", 0, 0);
                
        ServiceResponse<List<Featured>> response5 = featuredService2.readAll("quezon city", "1", 0, 0);
        ServiceResponse<List<Featured>> response6 = featuredService2.readAll("quezon city", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response7 = featuredService2.readAll("mandaluyong", "1", 0, 0);
        ServiceResponse<List<Featured>> response8 = featuredService2.readAll("mandaluyong", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response9 = featuredService2.readAll("pasig", "1", 0, 0);
        ServiceResponse<List<Featured>> response10 = featuredService2.readAll("pasig", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response11 = featuredService2.readAll("san juan", "1", 0, 0);
        ServiceResponse<List<Featured>> response12 = featuredService2.readAll("san juan", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response13 = featuredService2.readAll("pasay", "1", 0, 0);
        ServiceResponse<List<Featured>> response14 = featuredService2.readAll("pasay", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response15 = featuredService2.readAll("manila", "1", 0, 0);
        ServiceResponse<List<Featured>> response16 = featuredService2.readAll("manila", "2", 0, 0);
                
        ServiceResponse<List<Featured>> response17 = featuredService2.readAll("paranaque", "1", 0, 0);
        ServiceResponse<List<Featured>> response18 = featuredService2.readAll("paranaque", "2", 0, 0);
        
        ServiceResponse<List<Featured>> response19 = featuredService2.readAll("muntinlupa", "1", 0, 0);
        ServiceResponse<List<Featured>> response20 = featuredService2.readAll("muntinlupa", "2", 0, 0);
                
        ServiceResponse<List<Featured>> response21 = featuredService2.readAll("cebu", "1", 0, 0);
        ServiceResponse<List<Featured>> response22 = featuredService2.readAll("cebu", "2", 0, 0);
        
        List<Featured> featuredsMakati1 = response1.getResponse();  
        List<Featured> featuredsMakati2 = response2.getResponse();  
                        
        List<Featured> featuredsTaguig1 = response3.getResponse();  
        List<Featured> featuredsTaguig2 = response4.getResponse();  
                
        List<Featured> featuredsQuezonCity1 = response5.getResponse();  
        List<Featured> featuredsQuezonCity2 = response6.getResponse();  
        
        List<Featured> featuredsMandaluyong1 = response7.getResponse();  
        List<Featured> featuredsMandaluyong2 = response8.getResponse();  
        
        List<Featured> featuredsPasig1 = response9.getResponse();  
        List<Featured> featuredsPasig2 = response10.getResponse();  
        
        List<Featured> featuredsSanJuan1 = response11.getResponse();  
        List<Featured> featuredsSanJuan2 = response12.getResponse();  
        
        List<Featured> featuredsPasay1 = response13.getResponse();  
        List<Featured> featuredsPasay2 = response14.getResponse();  
        
        List<Featured> featuredsManila1 = response15.getResponse();  
        List<Featured> featuredsManila2 = response16.getResponse();  
        
        List<Featured> featuredsParanaque1 = response17.getResponse();  
        List<Featured> featuredsParanaque2 = response18.getResponse();  
        
        List<Featured> featuredsMuntinlupa1 = response19.getResponse();  
        List<Featured> featuredsMuntinlupa2 = response20.getResponse();  
        
        List<Featured> featuredsCebu1 = response21.getResponse();  
        List<Featured> featuredsCebu2 = response22.getResponse();  
        
        fillAttributes(featuredsMakati1);
        fillAttributes(featuredsMakati2);  

        fillAttributes(featuredsTaguig1);
        fillAttributes(featuredsTaguig2);  

        fillAttributes(featuredsQuezonCity1);
        fillAttributes(featuredsQuezonCity2);  

        fillAttributes(featuredsMandaluyong1);
        fillAttributes(featuredsMandaluyong2);  

        fillAttributes(featuredsPasig1);
        fillAttributes(featuredsPasig2);  

        fillAttributes(featuredsSanJuan1);
        fillAttributes(featuredsSanJuan2);  

        fillAttributes(featuredsPasay1);
        fillAttributes(featuredsPasay2);  

        fillAttributes(featuredsManila1);
        fillAttributes(featuredsManila2);  

        fillAttributes(featuredsParanaque1);
        fillAttributes(featuredsParanaque2);  

        fillAttributes(featuredsMuntinlupa1);
        fillAttributes(featuredsMuntinlupa2);  

        fillAttributes(featuredsCebu1);
        fillAttributes(featuredsCebu2);         
        
        map.put("featuredsMakati1", featuredsMakati1);
        map.put("featuredsMakati2", featuredsMakati2);

        map.put("featuredsTaguig1", featuredsTaguig1);
        map.put("featuredsTaguig2", featuredsTaguig2);

        map.put("featuredsQuezonCity1", featuredsQuezonCity1);
        map.put("featuredsQuezonCity2", featuredsQuezonCity2);

        map.put("featuredsMandaluyong1", featuredsMandaluyong1);
        map.put("featuredsMandaluyong2", featuredsMandaluyong2);

        map.put("featuredsPasig1", featuredsPasig1);
        map.put("featuredsPasig2", featuredsPasig2);

        map.put("featuredsSanJuan1", featuredsSanJuan1);
        map.put("featuredsSanJuan2", featuredsSanJuan2);

        map.put("featuredsPasay1", featuredsPasay1);
        map.put("featuredsPasay2", featuredsPasay2);

        map.put("featuredsManila1", featuredsManila1);
        map.put("featuredsManila2", featuredsManila2);

        map.put("featuredsParanaque1", featuredsParanaque1);
        map.put("featuredsParanaque2", featuredsParanaque2);

        map.put("featuredsMuntinlupa1", featuredsMuntinlupa1);
        map.put("featuredsMuntinlupa2", featuredsMuntinlupa2);

        map.put("featuredsCebu1", featuredsCebu1);
        map.put("featuredsCebu2", featuredsCebu2);
        
        mav.setViewName("featuredall_manage");   
    }
    
    private void createFeaturedListing_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        String type = request.getParameter("type");
        String termType = request.getParameter("termType");
        String city = request.getParameter("city");
        String listingID = request.getParameter("listingID");
        
        String paramStartDate = request.getParameter("startDate");
        String paramEndDate = request.getParameter("endDate");
        
        Date startDate = null;
        Date endDate = null;
        
        try { startDate = sdf.parse(paramStartDate); } catch (Exception ex) { }
        try { endDate = sdf.parse(paramEndDate); } catch (Exception ex) { }
        
        String strStartDate = "";
        String strEndDate = "";
        
        if (startDate != null) {
            sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
            strStartDate = sdf_utc.format(startDate);
        }
        if (endDate != null) {
            sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
            strEndDate = sdf_utc.format(endDate);
        }
        
        Featured featured = new Featured();
        featured.setType(type);
        featured.setTermType(termType);
        featured.setCity(city);
        featured.setListingID(listingID);
        
        featured.setStartDate(startDate);
        featured.setEndDate(endDate);
        
        featured.setStrStartDate(strStartDate);
        featured.setStrEndDate(strEndDate);
                
        
        boolean maxReached = featuredService2.checkMaxReached(city, termType).getResponse();
        boolean exisiting = featuredService2.checkExisting(listingID, city, termType).getResponse();
        boolean valid = featuredService2.checkListingValid(listingID).getResponse();
        
        if (!maxReached && !exisiting && valid) {         
            //CX: process payment
            //CX: if success, create
            featuredService2.create(featured);  
        }    
        mav.setView(new RedirectView("featured.htm?a=9021"));
    }
    
    private void deleteFeaturedListing_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");        
        featuredService2.delete(id);                    
        mav.setView(new RedirectView("featured.htm?a=9021"));
    }
    
    private void readAllFeaturedList(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        ServiceResponse<List<FeaturedList>> response = featuredService.readAllFeaturedList(StringUtils.isEmpty(offset) ? 0 : Integer.parseInt(offset), StringUtils.isEmpty(limit) ? 0 : Integer.parseInt(limit));
        
        List<FeaturedList> featuredLists = response.getResponse();
        if (featuredLists != null && featuredLists.size() > 0) {
            for (FeaturedList featured : featuredLists) {
                featured.setListing(listingService.read(featured.getListingID()).getResponse());                
            }
        } 
            
        map.put("featuredLists", featuredLists);
        mav.setViewName("featuredlists");   
    }
        
    private void createFeaturedList(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {                     
            String id = request.getParameter("id");            
            String listingID = request.getParameter("listingID");
                    
            FeaturedList featuredList = new FeaturedList();    
            featuredList.setId(id);
            featuredList.setListingID(listingID);
            
            ServiceResponse<String> response = featuredService.createFeaturedList(id, featuredList);
            mav.setView(new RedirectView("featured.htm?a="+FeaturedAction.READ_ALL_FEATURED_LIST));   
        }
        else {
            //CX: get amenity choices
            //CX: get amenity choices
            mav.setViewName("featuredlistadd");
        }
    }
    
    private void deleteFeaturedList(ModelAndView mav, Map map, HttpServletRequest request) {        
        String id = request.getParameter("id");
        ServiceResponse<Boolean> response = featuredService.deleteFeaturedList(id);        
        mav.setView(new RedirectView("featured.htm?a="+FeaturedAction.READ_ALL_FEATURED_LIST));
    }
        
    private void fillAttributes(List<Featured> featureds) {
        
        String strStartDateManila = "";
        String strEndDateManila = "";
        if (featureds != null && featureds.size() > 0) {
            for (Featured featured : featureds) {
                
                if (!StringUtils.isEmpty(featured.getStrStartDate())) {
                    sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
                    sdf_manila.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
                    try { strStartDateManila = sdf_manila.format(sdf_utc.parse(featured.getStrStartDate())); } catch (Exception ex) { }
                }    
                
                if (!StringUtils.isEmpty(featured.getStrEndDate())) {
                    sdf_utc.setTimeZone(TimeZone.getTimeZone("UTC"));
                    sdf_manila.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
                    try { strEndDateManila = sdf_manila.format(sdf_utc.parse(featured.getStrEndDate())); } catch (Exception ex) { }            
                }       
                
                featured.setStrStartDateManila(strStartDateManila);
                featured.setStrEndDateManila(strEndDateManila);
            }
        }
    }
    
    private void markFeaturedListings(List<Listing> listings, List<Featured> featureds) {
        if (listings != null && listings.size() > 0 && featureds!= null && featureds.size() > 0) {
            for (Listing listing : listings) {
                for (Featured featured : featureds) {
                    if (StringUtils.equalsIgnoreCase(featured.getListingID(), listing.getId())) {
                        listing.setFeatured(true);
                        listing.setCity_featured(featured.getCity());
                    }
                }
            }
        }
    }
}